package com.sniper.springmvc.action.admin;

import com.alibaba.druid.pool.DruidDataSource;
import com.sniper.springmvc.scheduler.BackDBToFile;
import com.sniper.springmvc.scheduler.JyzxImportWithScheduled;
import com.sniper.springmvc.scheduler.TaskStatus;
import com.sniper.springmvc.searchUtil.SchedulerSearch;
import com.sniper.springmvc.shiro.scheduler.QuartzManagerUtil;
import com.sniper.springmvc.utils.PathUtil;
import com.sniper.springmvc.utils.ScheduleJob;
import com.sniper.springmvc.utils.ValidateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 数据库管理
 *
 * @author sniper
 */
@Controller
@RequestMapping("${adminPath}/admin-tasks")
public class AdminTasksController extends AdminBaseController {

    @Resource(name = "dataSource_slave")
    private DruidDataSource dataSource;

    @RequiresPermissions("admin:tasks:view")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index(Map<String, Object> map) throws SchedulerException {

        map.put("jobs", QuartzManagerUtil.getCronJobs());
        return forward("/admin/admin-tasks/index.ftl");
    }

    @RequiresPermissions("admin:tasks:view")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public String index(Map<String, Object> map, SchedulerSearch search)
            throws SchedulerException {

        String jobName = "";
        if (ValidateUtil.isValid(search.getJobName())) {
            jobName = search.getJobName().trim();
        }

        String submit = search.getSubmit().trim();
        switch (TaskStatus.toTaskStatus(submit)) {
            case START:
                QuartzManagerUtil.start();
                break;
            case PAUSE:
                QuartzManagerUtil.pauseCronJob(jobName);
                break;
            case CONTINUE:
                QuartzManagerUtil.resumeJob(jobName);
                break;
            case STOP:
                QuartzManagerUtil.stop();
            case DELETE:
                QuartzManagerUtil.removeCronJob(jobName);
            case RUNONCE:
                break;

            default:
                break;
        }

        // 获取任务列表
        List<ScheduleJob> jobs = QuartzManagerUtil.getCronJobs();
        jobs.addAll(QuartzManagerUtil.getExecutingJobs());
        map.put("jobs", jobs);

        return forward("/admin/admin-tasks/index.ftl");
    }

    @RequiresPermissions("admin:tasks:job")
    @ResponseBody
    @RequestMapping(value = "job", method = RequestMethod.POST)
    public String job(SchedulerSearch search) throws SchedulerException {

        String jobName = search.getJobName();
        String submit = search.getSubmit().trim();

        switch (TaskStatus.toTaskStatus(submit)) {
            case START:
                QuartzManagerUtil.start();
                break;
            case PAUSE:
                QuartzManagerUtil.pauseCronJob(jobName);
                break;
            case CONTINUE:
                QuartzManagerUtil.resumeJob(jobName);
                break;
            case STOP:
                QuartzManagerUtil.stop();
            case RUNONCE:
                break;

            default:
                break;
        }

        return "";
    }

    @RequiresPermissions("admin:tasks:dbBackToFile")
    @RequestMapping(value = "dbBackToFile", method = RequestMethod.GET)
    public String backDBToFile(Map<String, Object> map)
            throws SchedulerException, IllegalAccessException {
        // 数据初始化
        // 储存地址初始化
        String jobName = BackDBToFile.jobName;
        SchedulerSearch search = new SchedulerSearch();
        ScheduleJob job = QuartzManagerUtil.getScheduleJob(jobName);
        if (job != null) {
            search.setCron(job.getCronExpression());
        }
        String webRootPath = PathUtil.getWebRoot();
        search.setCount(BackDBToFile.getFileCount());
        search.setPath(BackDBToFile.defaultPath);
        // 读取文件列表
        if (ValidateUtil.isValid(BackDBToFile.getBackToFilePath())) {
            search.setPath(BackDBToFile.getBackToFilePath());
            // 获取url后缀,用于下载
            String webRootPathSuffix = BackDBToFile.getBackToFilePath()
                    .substring(webRootPath.length());
            map.put("webRootPathSuffix", webRootPathSuffix);
        }

        System.out.println(dataSource.getUrl());
        map.put("search", search);
        map.put("job", job);
        map.put("files", BackDBToFile.getFiles());
        return forward("/admin/admin-tasks/backdbtofile.ftl");
    }

    @RequiresPermissions("admin:tasks:dbBackToFile")
    @RequestMapping(value = "dbBackToFile", method = RequestMethod.POST)
    public String backDBToFile(Map<String, Object> map, SchedulerSearch search)
            throws SchedulerException, IllegalAccessException {

        String jobName = BackDBToFile.jobName;
        BackDBToFile backDBToFile = new BackDBToFile();
        QuartzManagerUtil.start();
        // 更新任务时间
        String path = search.getPath().trim();
        String cron = search.getCron();
        String submit = search.getSubmit().trim();
        int count = search.getCount();

        BackDBToFile.setDataSource(dataSource);
        if (ValidateUtil.isValid(path)) {
            BackDBToFile.setBackToFilePath(path);
        }
        if (ValidateUtil.isValid(count)) {
            BackDBToFile.setFileCount(count);
        }

        switch (TaskStatus.toTaskStatus(submit)) {
            case START:
                if (ValidateUtil.isValid(cron)) {
                    QuartzManagerUtil.addCronJob(jobName, BackDBToFile.class, cron);
                }
                break;
            case PAUSE:
                QuartzManagerUtil.pauseCronJob(jobName);
                break;
            case CONTINUE:
                QuartzManagerUtil.resumeJob(jobName);
                break;
            case STOP:
                QuartzManagerUtil.removeCronJob(jobName);
                break;
            case RUNONCE:
                backDBToFile.init();
                break;

            default:
                break;
        }

        //执行完毕停止
        //QuartzManagerUtil.stop();

        String webRootPath = PathUtil.getWebRoot();
        if (ValidateUtil.isValid(BackDBToFile.getBackToFilePath())) {
            search.setPath(BackDBToFile.getBackToFilePath());
            // 获取url后缀,用于下载
            String webRootPathSuffix = BackDBToFile.getBackToFilePath().substring(webRootPath.length());
            map.put("webRootPathSuffix", webRootPathSuffix);

        }

        ScheduleJob job = QuartzManagerUtil.getScheduleJob(jobName);
        if (job != null) {
            search.setCron(job.getCronExpression());
        }

        map.put("files", BackDBToFile.getFiles());
        map.put("job", job);
        map.put("search", search);
        return forward("/admin/admin-tasks/backdbtofile.ftl");
    }

    @RequiresPermissions("admin:tasks:jyzx")
    @RequestMapping(value = "jyzx", method = RequestMethod.GET)
    public String jyzx(Map<String, Object> map)
            throws SchedulerException {

        String jobName = JyzxImportWithScheduled.jobName;
        SchedulerSearch search = new SchedulerSearch();
        ScheduleJob job = QuartzManagerUtil.getScheduleJob(jobName);
        if (job != null) {
            search.setCron(job.getCronExpression());
        }
        map.put("job", job);
        map.put("search", search);
        return forward("/admin/admin-tasks/jyzx.ftl");
    }

    @RequiresPermissions("admin:tasks:jyzx")
    @RequestMapping(value = "jyzx", method = RequestMethod.POST)
    public String jyzx(Map<String, Object> map, SchedulerSearch search)
            throws SchedulerException, IOException,
            ParseException {
        String jobName = JyzxImportWithScheduled.jobName;
        QuartzManagerUtil.start();


        // 更新任务时间
        String cron = search.getCron();
        String submit = search.getSubmit().trim();


        switch (TaskStatus.toTaskStatus(submit)) {
            case START:
                if (ValidateUtil.isValid(cron)) {
                    QuartzManagerUtil.addCronJob(jobName, JyzxImportWithScheduled.class, cron);
                }
                break;
            case PAUSE:
                QuartzManagerUtil.pauseCronJob(jobName);
                break;
            case CONTINUE:
                QuartzManagerUtil.resumeJob(jobName);
                break;
            case STOP:
                QuartzManagerUtil.removeCronJob(jobName);
                break;
            case RUNONCE:
                QuartzManagerUtil.addRepeatJob(JyzxImportWithScheduled.jobName, JyzxImportWithScheduled.class, 1, 1, new Date());
                break;

            default:
                break;
        }
        //执行完毕停止
        //QuartzManagerUtil.stop();

        ScheduleJob job = QuartzManagerUtil.getScheduleJob(jobName);
        if (job != null) {
            search.setCron(job.getCronExpression());
        }

        map.put("search", search);
        map.put("job", job);
        return forward("/admin/admin-tasks/jyzx.ftl");
    }


}